const { goodsFormatError } = require('../constant/error.type')

const validator = async (ctx, next) => {
  try {
    // 参数校验
    ctx.verifyParams({
      goods_name: { type: 'string', required: true },
      goods_price: { type: 'number', required: true, min: 0 },
      goods_num: { type: 'number', required: true, min: 1 },
      goods_img: { type: 'string', required: true },
    })
  } catch (e) {
    console.error('请求参数格式错误', e)
    goodsFormatError.result = e.errors
    return ctx.app.emit('error', goodsFormatError, ctx)
  }

  await next()
}

const validateQuery = async (ctx, next) => {
  const { pageNum = 1, pageSize = 10 } = ctx.request.query

  if (isNaN(pageNum) || Math.abs(pageNum) === 0) {
    delete ctx.request.query.pageNum
  } else {
    ctx.request.query.pageNum = Math.abs(pageNum)
  }

  if (isNaN(pageSize)) {
    delete ctx.request.query.pageSize
  } else {
    ctx.request.query.pageSize = Math.abs(pageSize)
  }

  if (ctx.request.query.status) {
    const { status } = ctx.request.query
    if (isNaN(status)) {
      ctx.request.query.status = 0
    } else {
      ctx.request.query.status = Math.abs(status)
    }
  }

  await next()
}

module.exports = {
  validator,
  validateQuery,
}
